<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use app\admin\model\MessageApi;
/**
 * 房间管理
 *
 * @icon fa fa-circle-o
 */
class Fangjian extends Backend
{

    /**
     * Fangjian模型对象
     * @var \app\admin\model\Fangjian
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Fangjian;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['category'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('category')->visible(['name', 'dizhi', 'phone']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = input('')['row'];
            if (!$data['name']) {
                return $this->error("请输入包房名称");
            }
            if (!$data['type']) {
                return $this->error("请输入类型");
            }
            if (!$data['price']) {
                return $this->error("请输入价格");
            }
            if (!$data['booking_time']) {
                return $this->error("请输入起订小时");
            }
            if (!$data['image']) {
                return $this->error("请上传图片");
            }
            $res = Db::name('fangjian')->insertGetId([
                'type' => $data['type'],
                'price' => $data['price'],
                'createtime' => time(),
                'category_id' => $data['category_id'],
                'name' => $data['name'],
                'image' => $data['image'],
                'package_vip_price' => $data['package_vip_price'],
                'biaoqian' => $data['biaoqian'],
                'images' => $data['images'],
                'room_lock_id' => $data['room_lock_id'],
                'dian_id' => $data['dian_id'],
                'booking_time' => $data['booking_time'],
                'duration' => $data['duration'],
                'message_devid' => $data['message_devid'],
            ]);
            if (isset($data['package']) && $data['package']) {
                $packages = [];
                foreach ($data['package'] as $package) {
                    $packages[] = [
                        'fj_id' => $res,
                        'price' => $package['price'],
                        'times' => $package['times'],
                        'uniacid' => config('site.uniacid')
                    ];
                }
                Db::name('fangjian_package')->insertAll($packages);
            }
            if (!$res) {
                return $this->error("操作失败");
            }
            return $this->success('操作成功');
        }
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $data = input('')['row'];
            if (!$data['name']) {
                return $this->error("请输入包房名称");
            }
            if (!$data['type']) {
                return $this->error("请输入类型");
            }
            if (!$data['price']) {
                return $this->error("请输入价格");
            }
            if (!$data['booking_time']) {
                return $this->error("请输入起订小时");
            }
            if (!$data['image']) {
                return $this->error("请上传图片");
            }
            $res = Db::name('fangjian')->where([
                'id' => $ids
            ])->update([
                'type' => $data['type'],
                'price' => $data['price'],
                'name' => $data['name'],
                'image' => $data['image'],
                'biaoqian' => $data['biaoqian'],
                'images' => $data['images'],
                'room_lock_id' => $data['room_lock_id'],
                'package_vip_price' => $data['package_vip_price'],
                'dian_id' => $data['dian_id'],
                'booking_time' => $data['booking_time'],
                'duration' => $data['duration'],
                'message_devid' => $data['message_devid'],
            ]);
            Db::name('fangjian_package')->where(['fj_id' => $ids])->delete();
            if (isset($data['package']) && $data['package']) {
                $packages = [];
                foreach ($data['package'] as $package) {
                    $packages[] = [
                        'fj_id' => $ids,
                        'price' => $package['price'],
                        'times' => $package['times'],
                        'uniacid' => config('site.uniacid')
                    ];
                }
                Db::name('fangjian_package')->insertAll($packages);
            }
            if ($res === false) {
                return $this->error("操作失败");
            }
            return $this->success('操作成功');
        }
        $row = Db::name('fangjian')->where('id', $ids)->find();
        $package = Db::name('fangjian_package')->where(['fj_id' => $ids])->select();
        if ($package) {
            $package = json_encode($package, JSON_UNESCAPED_UNICODE);
        } else {
            $package = json_encode([], JSON_UNESCAPED_UNICODE);
        }
        $row['package'] = $package;
        $this->assign('row', $row);
        return $this->view->fetch();
    }

    public function closing()
    {
        $ids = $this->request->param("ids");
        $data = Db::name('fangjian')->alias('b')
            ->field("b.id,b.dian_id")
            ->where("id", $ids)
            ->find();
        if (!$data) {
            $this->error("房间不存在");
        }
        if (!$data['dian_id']) {
            $this->error("房间关电命令不存在");
        }
        $res = Db::name("diancommand")->insert([
            'fangjian_id' => $data['id'],
            'status' => 2,
            'is_status' => 0,
            'create_time' => time(),
        ]);
        if (!$res) {
            $this->error("写入失败");
        }
        $this->success('等待服务器发送,耐心等待几秒钟');
    }

    public function opening()
    {
        $ids = $this->request->param("ids");
        $data = Db::name('fangjian')->alias('b')
            ->field("b.id,b.dian_id")
            ->where("id", $ids)
            ->find();
        if (!$data) {
            $this->error("房间不存在");
        }
        if (!$data['dian_id']) {
            $this->error("房间开电命令不存在");
        }
        $res = Db::name("diancommand")->insert([
            'fangjian_id' => $data['id'],
            'status' => 1,
            'is_status' => 0,
            'create_time' => time(),
        ]);
        if (!$res) {
            $this->error("写入失败");
        }
        $this->success('等待服务器发送,耐心等待几秒钟');
    }

    public function dasaoing()
    {
        $ids = $this->request->param("ids");
        Db::name('fangjian')
            ->where("id", $ids)
            ->update(['is_dasao' => 1]);
        $this->success('操作成功');

    }

    public function dasaoer()
    {
        $ids = $this->request->param("ids");
        Db::name('fangjian')
            ->where("id", $ids)
            ->update(['is_dasao' => 0]);
        $this->success('操作成功');
    }
    
    public function message()
    {
          
        $ids = $this->request->param("ids");
        $message_devid =  Db::name('fangjian')
            ->where("id", $ids)
            ->value('message_devid');
            // $message_devid='11';
        if(!$message_devid){
              $this->error('未配置喇叭');
        }
        $oMessageApi = new MessageApi();
       $res=  $oMessageApi->send($message_devid, '喇叭设备测试正常');
       if($res === true){
           $this->success('操作成功');
       }
     
        $this->error("测试不成功：".$res);
    }
}
